package com.yang.aiDoctor.Impl;

import com.yang.aiDoctor.service.AIService;
import com.yang.aiDoctor.service.ChatRecordService;
import com.yang.aiDoctor.utils.ChatTypeEnum;
import com.yang.aiDoctor.utils.SSEMsgType;
import com.yang.aiDoctor.utils.SSEServer;
import groovy.util.logging.Slf4j;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;

@lombok.extern.slf4j.Slf4j
@Slf4j
@Service
public class AIServiceImpl implements AIService {

    private final OpenAiChatModel chatModel;

    @Resource
    private ChatRecordService chatRecordService;

    @Autowired
    public AIServiceImpl(OpenAiChatModel chatModel) {
        this.chatModel = chatModel;
    }

    @Override
    public Map aiChat(String message) {
        return Map.of("generation", this.chatModel.call(message));
    }

    @Override
    public Flux<ChatResponse> aiChatStream(String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        log.info(prompt.toString());
        return this.chatModel.stream(prompt);
    }

    @Override
    public List<String> aiChatStream2(String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        log.info(prompt.toString());
        Flux<ChatResponse> responseFlux = this.chatModel.stream(prompt);
        List<String> list = responseFlux.toStream().map(chatResponse -> {
            String text = chatResponse.getResult().getOutput().getText();
            log.info(text);
            return text;
        }).toList();
        log.info("list:{}", list);
        return list;
    }

    @Override
    public String chatWithDoctor(String userName, String message) {
        if (message == null || message.isEmpty()) {
            return "message is empty";
        }
        // 保存用户消息
        chatRecordService.saveChatRecord(userName, message, ChatTypeEnum.USER);

        Prompt prompt = new Prompt(new UserMessage(message));
        log.info(prompt.toString());
        List<String> list = this.chatModel.stream(prompt).toStream().map(chatResponse -> {
            String text = chatResponse.getResult().getOutput().getText();
            SSEServer.sendMessage(userName, text, SSEMsgType.ADD);
            return text;
        }).toList();

        SSEServer.sendMessage(userName, "finish", SSEMsgType.FINISH);

        StringBuilder htmlRes= new StringBuilder();
        for (String s : list) {
            htmlRes.append(s);
        }
        // 保存AI消息
        chatRecordService.saveChatRecord(userName, htmlRes.toString(), ChatTypeEnum.BOT);

        return "success";
    }
}
